<template>
  <ele-page flex-table>
    <ComHeader :title="`入库通知单详情[${info?.order_sn}]`" @back="goBack" />
    <ele-bottom-bar v-if="active === '1'" :teleported="true">
      <div class="flex-a">
        <template v-if="info.is_ys">
          <div>新增验收单：</div>
          <el-switch
            v-model="showEdit"
            inline-prompt
            @change="switchChange"
          />
        </template>
        <template v-if="showEdit">
          <el-divider class="mx-20px" direction="vertical" />
          <el-button type="primary" :loading="loading" plain @click="save">提交验收审核</el-button>
          <el-button type="" plain @click="showEdit = false">返回</el-button>
        </template>
      </div>
      <template #extra>
        <el-space :spacer="spacer">
          <el-button type="" icon="IconElPrinter" @click="openPrintProduct">商品标签</el-button>
          <el-button type="" @click="openPrint">打印单据</el-button>
          <el-button v-if="!showEdit && info.is_cd" type="" @click="cancel">取消订单</el-button>
          <el-button v-if="!showEdit && info.is_ok" type="primary" :loading="loading" @click="confirm">收货完成</el-button>
        </el-space>
      </template>
    </ele-bottom-bar>

    <ele-card flex-table bordered :header-style="{ padding: '0 16px' }">
      <template #header>
        <ele-tabs
          v-model="active"
          :items="[
            { name: '1', label: '基础信息' },
            { name: '2', label: '验收单列表' },
          ]"
          type="plain"
        />
      </template>
      <el-scrollbar v-show="active === '1'">
        <div>
          <el-descriptions title="" :column="4">
            <el-descriptions-item :width="100" label="入库通知单">
              <ele-copyable>{{ info.order_sn }}</ele-copyable>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="关联单号">
              <ele-copyable v-if="info.obj_sn">{{ info.obj_sn }}</ele-copyable>
              <span v-else>-</span>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="货主">
              {{ info.supplier_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="收货仓库">
              {{ info.warehouse_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="入库类型">
              <el-tag :type="getType(info.type)">{{ info.type_name }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="通知收货数量">
              {{ info.notice_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="验收数量">
              {{ info.review_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="入库数量">
              {{ info.enter_num || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="订单状态">
              <el-tag
                v-if="info.status_name"
                :type="getType(info.status)"
              >
                {{ info.status_name }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建人">
              {{ info.create_user_name || '-' }}
            </el-descriptions-item>
            <el-descriptions-item :width="100" label="创建时间">
              {{ info.create_time ? formatDate(info.create_time) : '-' }}
            </el-descriptions-item>

            <el-descriptions-item :span="2" label="备注">
              {{ info.remark || '-' }}
            </el-descriptions-item>
          </el-descriptions>

          <el-descriptions class="mt-20px" title="商品信息" :column="1">
            <template v-if="showEdit && info.is_add" #extra>
              <div class="mx-20px">
                <el-button :disabled="loading" @click="showProduct = true">添加商品</el-button>
              </div>
            </template>
          </el-descriptions>

          <el-form ref="formRef" label-suffix="" class="overflow-hidden" :model="{ product: info.product }" :rules="rules" label-width="auto">
            <el-form-item label="" label-position="top" label-width="200px" prop="product">
              <el-table
                :data="info.product"
                border
                style="width: 100%"
                show-summary
                :summary-method="getSummaries"
                class="form-table"
              >
                <el-table-column type="index" label="序" width="60" align="center" />
                <el-table-column prop="product_name" label="商品名称" align="left" :min-width="showEdit ? 200 : 160" />
                <el-table-column prop="product_code" label="商品编码" align="center" min-width="120" />
                <el-table-column prop="price" label="价格" align="center" min-width="110" />
                <el-table-column prop="unit" label="主单位" align="center" min-width="110" />
                <el-table-column prop="notice_num" label="通知收货数量" align="center" :show-overflow-tooltip="false" :width="Math.max(...info.product.map(v => v.multi_unit?.length), 1) * 50 + 80 ">
                  <template #default="{ row }">
                    <div class="flex-ca">
                      <div>{{ row.notice_num }}</div>
                      <div v-for="(item, i) in (row.unit_list || row.multi_unit).slice(1)" :key="i" class="text-info"><span class="mx-2px">=</span>{{ Big(row.notice_num).div(item.ratio).round(4).valueOf() }}{{ item.unit }}</div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="enter_num" label="已入库数量" align="center" min-width="110" />
                <el-table-column prop="review_num" label="验收数量" align="center" min-width="110" />
                <template v-if="showEdit">
                  <el-table-column prop="num" label="提审数量" align="center" :width="Math.max(...info.product.map(v => v.multi_unit?.length), 1) * 110 + 60">
                    <template #default="{ row, $index }">
                      <div class="flex-a">
                        <el-space>
                          <el-form-item
                            v-for="(item, i) in row.multi_unit"
                            :key="i"
                            :label-width="0"
                            :prop="`product[${$index}].multi_unit[${i}].num`"
                          >
                            <el-input
                              v-model="item.num"
                              class="w-90px!"
                              placeholder="数量"
                              oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                            >
                              <template #suffix><span class="text-#333!">{{ item.unit }}</span></template>
                            </el-input>
                          </el-form-item>
                        </el-space>
                        <div v-if="row.multi_unit?.length > 1" class="flex-shrink-0 min-w-60px ml-4px text-left">
                          = {{ totalUnit(row.multi_unit) }}{{ row.unit }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="review_num" label="差异" align="center" /> -->
                  <el-table-column prop="location" label="库位" align="center" :width="180">
                    <template #default="{ row, $index }">
                      <el-form-item
                        :label-width="0"
                        :prop="`product[${$index}].location_id`"
                        :required="row.multi_unit.some(v => Number(v.num))"
                      >
                        <el-cascader
                          v-model="row.location_id"
                          :options="locationTree"
                          filterable
                          clearable
                          placeholder="请选择库位"
                          :show-all-levels="false"
                          placement="left"
                          :props="{ value: 'id', label: 'name', expandTrigger: 'hover', emitPath: false }"
                        />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column column-key="action" label="操作" fixed="right" align="center" :width="100">
                    <template #default="{ row, $index }">
                      <div v-if="row.id">-</div>
                      <el-link v-else type="danger" underline="never" @click="info.product.splice($index, 1)">删除</el-link>
                    </template>
                  </el-table-column>
                </template>
                <!-- <el-table-column v-if="info.type === 'CG'" prop="revise_num" label="修正数量" align="center" /> -->
              </el-table>
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>
      <PageCheck v-if="active === '2'" :orderId="orderId" @done="getInfo" />
    </ele-card>

    <SelectProduct
      v-model="showProduct"
      :selecteds="info.product"
      :where="{ supplier_id: info.supplier_id, warehouse_id: info.warehouse_id }"
      @done="selectProduct"
    />

    <PagePrint v-model="showPrint" :objId="info.id" />
    <PrintProduct v-model="showPrintProduct" :data="info.product" :createTime="info.create_time" :warehouseId="info.warehouse_id" />
  </ele-page>
</template>

<script setup>
import { listWlList } from '@/api/common'
import PrintProduct from '@/components/Common/PrintProduct.vue'
import SelectProduct from '@/components/Common/SelectProduct/index.vue'
import { toTree } from 'ele-admin-plus/es'
import PagePrint from '../components/print.vue'

import PageCheck from './components/check.vue'

defineOptions({ name: 'EnterNoticeInfo' })

const orderId = ref(0)
const route = useRoute()
const router = useRouter()
const { routeTabKey, removePageTab, setPageTabTitle } = utils.usePageTab()
const { formatDate, totalUnit, getType, spacer, Big } = utils
const info = ref({ product: [] })
const active = ref('1')

const formRef = ref(null)

const rules = reactive({})

const loading = ref(false)
const showEdit = ref(false)
const showProduct = ref(false)
const showPrintProduct = ref(false)

const locationTree = ref([])
const locationList = ref([])
const showPrint = ref(false)
function openPrint() {
  showPrint.value = true
}

function openPrintProduct() {
  showPrintProduct.value = true
}

onMounted(() => {
  orderId.value = route.params?.id
  getInfo()
})

function goBack() {
  removePageTab({ key: routeTabKey })
  router.push('/enter/notice')
}

function getLocList() {
  listWlList(info.value.warehouse_id).then((res) => {
    locationList.value = res.data
    locationTree.value = toTree({
      data: res.data,
      idField: 'id',
      parentIdField: 'pid',
    })
  })
}

const defLocation = computed(() => locationList.value.filter(v => v.type === 1 && v.level === 3).sort((a, b) => b.is_def - a.is_def))

function getProductLoc() {
  const products = info.value.product.filter(f => !f.location)
  const productIds = products.map(v => v.product_id)
  if (!productIds.length) {
    return
  }
  utils.get('/warehouseLocation/product', {
    product_ids: productIds.toString(),
    warehouse_id: info.value.warehouse_id,
    is_location: 1,
  }).then((res) => {
    res.data.forEach((v) => {
      const index = info.value.product.findIndex(d => d.product_id === Number(v.product_id))
      if (v.location.length) {
        v.location.sort((a, b) => a.type - b.type)
      }
      else {
        v.location = defLocation.value
      }
      info.value.product[index] = {
        ...info.value.product[index],
        location: true,
        location_id: v.location.length ? v.location[0].id : '',
      }
    })
  })
}

watch(() => info.value.warehouse_id, (newVal) => {
  if (newVal) {
    getLocList()
  }
}, { immediate: true })

function switchChange(value) {
  if (value) {
    info.value.product.forEach((v) => {
      v.multi_unit = v.multi_unit.map(d => ({ ...d, num: '' }))
    })
    console.log(info.value.product)
    getProductLoc()
  }
}

function getInfo() {
  utils.get('/enterNotice/info', { id: orderId.value }).then((res) => {
    info.value = res.data

    setPageTabTitle(`入库通知单[${utils.ellipsisStr(res.data.order_sn, 0, 10)}]`)
  })
}

function selectProduct(data) {
  data.forEach((v) => {
    // v.multi_unit = v.unit_list.map(d => ({ ...d, num: '' }))
    v.multi_unit = utils.totalUnit(v.multi_unit) > 0 ? v.multi_unit : v.unit_list.map(d => ({ ...d, num: '' }))
    v.id = undefined
  })
  info.value.product.push(...data)
  getProductLoc()
}

function confirm() {
  utils.confirm('是否确定收货完成', '提示').then(() => {
    utils.post('/enterNotice/ok', { id: info.value.id }).then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        getInfo()
      }
    })
  })
}

function cancel() {
  const opts = {
    type: 'warning',
    dangerouslyUseHTMLString: true,
    cancelButtonText: '不取消了',
    confirmButtonText: '确定取消',
  }
  utils.confirm(`确定要<span class="px-2px text-danger font-semibold">取消</span>订单吗`, '系统提示', opts).then(() => {
    const Loading = utils.message('请求中..', 'loading')
    utils.post('/enterNotice/cancel', { id: [info.value.id] }).then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        getInfo()
      }
    }).finally(() => {
      Loading.close()
    })
  })
}

function save() {
  formRef.value?.validate?.((valid) => {
    if (!valid)
      return

    const product = utils.cloneDeep(info.value.product).reduce((acc, cur) => {
      const num = totalUnit(cur.multi_unit)
      if (num > 0) {
        acc.push({
          product_id: cur.product_id,
          multi_unit: cur.multi_unit,
          review_num: num,
          location: [{
            id: cur.location_id,
            name: locationList.value.find(v => v.id === cur.location_id)?.name ?? '',
            num,
          }],
        })
      }
      return acc
    }, [])

    if (!product.length) {
      return utils.message.error('请填写提审商品数量')
    }

    loading.value = true

    const formData = {
      oen_id: info.value.id,
      product,
    }

    utils.post('/enterNotice/check', formData)
      .then((res) => {
        utils.message(res.msg, res.success)
        if (res.success) {
          getInfo()
          showEdit.value = false
        }
      })
      .finally(() => {
        loading.value = false
      })
  })
}

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['notice_num', 'review_num', 'enter_num', 'num', 'revise_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => {
        const num = column.property === 'num' ? utils.totalUnit(cur.multi_unit) : cur[column.property]
        return utils.Big(acc).plus(num).valueOf()
      }, 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped></style>
